<template>
	<!-- 骨架屏 -->
	<SkeletonScreen v-if="loading"></SkeletonScreen>
	<view>
		<!-- 页面头部返回和搜索图标，标题 -->
		<my-Back-search style="position: relative; z-index: 1000;" :yesSearch="false">
			<template #back>
				<uni-icons @click="onBack" type="back" size="28" color="#ff0000"></uni-icons>

			</template>
			<template #time>
				<view>{{videos.name}}</view>
			</template>
			<template #search>
				<uni-icons @click="toggleDropdown" type="bars" size="28" color="#ff0000"></uni-icons>
				<DropdownMenu :showDropdown="showDropdown"></DropdownMenu>
			</template>
		</my-Back-search>

		<view v-if="videoIf">
			<video style="height: 420rpx;width: 100%; position: fixed;z-index: 101;" id="myVideos" direction="90"
				@ended="onbindended" :show-fullscreen-btn="false" :show-play-btn="fasle" :show-center-play-btn="false"
				:enable-progress-gesture="fasle" :show-progress="false" :show-bottom-progress="fasle" :autoplay="true"
				:src="textSrc" :controls="false"></video>
		</view>
		<video style="height: 420rpx;width: 100%; position: fixed;z-index: 100;" id="myVideo" :src="NewVideoUrl"
			:title="videos.name" controls="true" autoplay="true" show-fullscreen-btn show-play-btn show-center-play-btn
			enable-progress-gesture :enable-play-gesture="true" auto-pause-if-navigate vslide-gesture-in-fullscreen
			show-bottom-progress :show-snapshot-button="true" :show-casting-button="true"
			:enable-auto-rotation="!videoIf" :show-screen-lock-button="true" :picture-in-picture-mode="['push','pop']"
			@ended="videoEnded" @timeupdate="handleTimeUpdate" ref="videoPlayer" @play="onPlay">
			<!-- 开通会员的提示 -->
			<view class="video-center" v-if="showVipModal">
				<view class="center-title">本片是由平台VIP会员专享内容</view>
				<view class="center-title2">试看已结束，继续观看请开通VIP会员</view>
				<view @click="huiyuanFunction" class="center-text">开通会员</view>
			</view>
		</video>
		<view style="height: 420rpx;"></view>


		<!-- video信息 -->
		<view class="video-content">

			<view class="content-title">
				<view class="video-title">{{videos.name}}</view>
				<view></view>
			</view>

			<view style="display: flex; align-items: center; ">
				<!-- 只读状态 -->
				<uni-rate allow-half size="12" :readonly="true" :value="videos.bifen" max="6" />
				<view style="font-size: 20rpx; color:#ff0000;">&nbsp;&nbsp;{{videos.bifen}}</view>
			</view>

			<!-- video相关信息 -->
			<view class="video-sort">
				<view>{{videos.year}}</view>
				<view>|</view>
				<view>{{videos.yurts}}</view>
				<view>|</view>
				<view>
					<text style="margin-right: 20rpx;" v-for="item in videos.tags">{{item.name}}</text>
				</view>

			</view>
		</view>


		<!-- 分享与下载按钮 -->
		<view class="bottum">
			<!-- 推荐 -->
			<view @tap="handFunction(videos.id)">
				<view class="bottum-Bg">
					<uni-icons :type="handIcon" size="28" color="#fff"></uni-icons>
				</view>
				<view class="bottum-text">推荐</view>
			</view>

			<!-- 收藏 -->
			<view @tap="starFunction(videos.id)">
				<view class="bottum-Bg">
					<uni-icons :type="starIcon" size="28" color="#fff"></uni-icons>
				</view>
				<view class="bottum-text">收藏</view>
			</view>



			<!-- 赚钱 -->
			<view @click.stop="openImg(1)">
				<view class="bottum-Bg">
					<uni-icons type="gift" size="28" color="#fff"></uni-icons>
				</view>
				<view class="bottum-text">赚钱</view>
			</view>

			<!-- 分享 -->
			<view @tap="open">
				<view class="bottum-Bg">
					<uni-icons type="redo" size="28" color="#fff"></uni-icons>
				</view>
				<view class="bottum-text">分享</view>
			</view>
		</view>

		<!-- 简介 -->
		<max-title-min :isIcon="false" title="简介"></max-title-min>
		<view class="text-title">
			<ExpandableText :text="videos.content" :default-lines="3" font-size="24" text-color="#969696"
				toggle-color="#ff0000" />
		</view>


		<!-- 演职 -->
		<view v-if="videos.type == 1">
			<max-title-min :isIcon="false" title="演职员"></max-title-min>
			<my-scroll-actor :list="actors"></my-scroll-actor>
		</view>


		<!-- 选集 -->
		<view v-if="videos.episode">
			<max-title-min :isIcon="false" title="选集"></max-title-min>
			<!-- 选季 -->
			<view style="padding: 0 0 20rpx 10rpx;margin-top: -30rpx;">
				<my-scroll-navbar style=" padding: 0 " v-if="videos.season > 0" :curIndexx="videos.season-1"
					:isIcon="false" @TagIndex="seasonFunction" :isNav="false" :list="seasonValue"></my-scroll-navbar>
			</view>

			<!-- 选集 -->
			<scroll-view class="han-category-scroll" scroll-x>
				<view class="category">
					<view class="c-item" v-for="(item ,index ) in videoUrlSize">
						<view>
							<view class="usji" @click="xuanjiFunction(index)">
								<view>{{item.videoJi}}</view>
								<view class="spinner" v-if="urlIndex==index && urlIndexif">
									<view class="rect1"></view>
									<view class="rect2"></view>
									<view class="rect3"></view>
									<view class="rect4"></view>
								</view>
								<view class="usji-vip" v-if="item.status == 2 ">
									<view class="usji-vip-title">VIP</view>
								</view>
							</view>
							<view class="c-name"></view>
						</view>
					</view>
				</view>
			</scroll-view>

		</view>

		<!-- 评论等等相关导航 -->

		<my-scroll-navbar @TagIndex="onNavbar" :isNav="false" style="padding-top: 10rpx;" :list="commentNavbar"
			:commentCount="commendTotal"></my-scroll-navbar>

		<!-- 摘要与推荐 -->
		<view v-if="onIndex == 0">
			<!-- 摘要 -->
			<view class="image-eight-Three">
				<my-Swiper-min-max :iSautoplay="true" :iStitle="false" :games="true" :minImages="imagesBanner"
					:images="videos.imageUrl"></my-Swiper-min-max>
			</view>

			<!-- 最后底部触发 -->
			<view class="image-eight" style="padding-bottom: 20rpx;">
				<my-img-y v-for="item in imgListThrea" :key="item.id" :urlId="item.id" :images="item.imageUrl"
					:tags="item.tags" :name="item.name" :bifen="item.bifen" :biao="item.biao"
					:sort="item.type"></my-img-y>
			</view>

		</view>


		<!-- 讨论 -->
		<view v-if="onIndex == 1">
			<view class="comment" v-for="(item , index) in commends">
				<view class="com-user">
					<view>
						<image class="userImg" :src="item.userImg"></image>
					</view>
					<!-- hand-down-filled ｜｜ hand-up-filled  -->
					<view class="com-SetCount">
						<view class="hand-up">
							<uni-icons @click="iconClick(index)" :type="item.condIconyes" size="20"
								color="#ff0000"></uni-icons>
							<!-- <view style="font-size: 20rpx; color:#969696 ; margin-left: 5rpx;">0</view> -->
						</view>
						<view style="text-align: center;">
							<uni-icons @click="iconClickno(index)" :type="item.condIconno" size="20"
								color="#ff0000"></uni-icons>
						</view>

					</view>

				</view>

				<view class="comment-content">
					<view class="com-user-time">
						<view>{{item.username}}</view>
						<view>{{item.time}}</view>
					</view>
					<view class="text-title">
						<hbxw-text-folding :fontSize="24" color="#969696" ellipsisColor="#969696"
							:btnStyle="{backgroundColor: 'transparent',color: 'red', padding: '0 8rpx'}">{{item.content}}</hbxw-text-folding>
					</view>
				</view>


			</view>
			<view style="height: 110rpx;"></view>

			<!-- 写一下评论 -->
			<view class="commendfa">
				<input class="fa-input" @confirm="onCommend" type="text" confirm-type="发送" adjust-position
					placeholder="留下美好的感受吧！" v-model="commendModel" />
				<view class="fa-bottum" @click="onCommend">发送</view>
			</view>

		</view>

		<!-- 分享 -->
		<view style="width: 500rpx;">
			<uni-popup borderRadius="20rpx" style="width: 500rpx;" is-mask-click background-color="#1d1d1d" ref="popup"
				type="share">
				<uni-popup-share title="分享到" @select="select">
					<template #share>
						<view class="share-pop">
							<view class="pop-item">
								<button class="b-abs" open-type="share" size="mini" plain="true">
									<uni-icons type="weixin" size="30" color="#ff0000"></uni-icons>
								</button>
								<view>转发</view>
							</view>
							<view class="pop-item">
								<button @click.stop="openImg(1)" class="b-abs" size="mini" plain="true">
									<uni-icons type="pyq" size="30" color="#ff0000"></uni-icons>
								</button>
								<view>朋友圈</view>
							</view>

							<view class="pop-item">
								<button @click.stop="openImg(2)" class="b-abs" size="mini" plain="true">
									<uni-icons type="scan" size="30" color="#ff0000"></uni-icons>
								</button>

								<view>通用码</view>
							</view>
							<view class="pop-item">
								<button class="b-abs" @click.stop="createLink(1)" size="mini" plain="true">
									<uni-icons type="link" size="30" color="#ff0000"></uni-icons>
								</button>

								<view>https链接</view>
							</view>
						</view>
					</template>
				</uni-popup-share>
			</uni-popup>
		</view>

		<view>
			<!-- 海报生成器 -->
			<piaoyi-poster ref="piaoyiPostor" @temp-file-path="tempFilePath" :img-image="img" :shop-name="videos.name"
				:title="title" :detail="detail" :price="price" :imgImage="videos.imageUrl" :yurts="videos.yurts"
				:qrImage="qrImage" :years="videos.year" :tags1="videos?.tags[0]?.name" :tags2="videos?.tags[1]?.name"
				:tags3="videos?.tags[2]?.name" />

			<!-- 小程序码生成器 -->
			<QrCodeGenerator ref="CodeGenerator" page="pages/play/play" :scene="{ id: videoId, userId: userId }"
				:autoColor="true" :color="{ r: 0, g: 0, b: 0 }" envVersion="release" @success="onQrCodeSuccess"
				@error="onQrCodeError" @loading="onLoading" />

			<!-- 通用二维码生成器 -->
			<QRLightGenerator ref="Generator" :url="targetUrl" :icon="logoIcon" @generated="onQRGenerated"
				@cleared="onQRCleared" />


			<!-- 展示生成后的海报图 v-if="posterIf"-->
			<view class="poster-img" @touchmove.stop v-if="posterIf">
				<view class="poster-icon">
					<navigator url="/pages/geid/coins/coins">
						<uni-icons type="help" size="30" color="#ff0000"></uni-icons>
					</navigator>
					<view>

					</view>

					<view @click="posterClose">
						<uni-icons type="close" size="30" color="#ff0000"></uni-icons>
					</view>
				</view>
				<!-- :src="img" -->
				<view style="width: 80%;height: 55%;">
					<image :src="img" style="width: 100%;height: 100%;" show-menu-by-longpress></image>
				</view>
				<!-- 导航 -->
				<view class="share">
					<view @click.stop="shareImgFunction">保存</view>
				</view>

			</view>
		</view>
	</view>
</template>


<script setup>
	import {
		ref,
		onMounted
	} from 'vue';
	import {
		videoById,
		actorById,
		ImgById,
		swiperimgsBanner,
		VideoCommend,
		insertCommend,
		videoUrls,
		seriesVideo,
		insertCollent,
		collectionCollent,
		insertRecommend,
		collectionRecommend,
		WatchUpdate

	} from '@/API/playApis.js';
	import {
		onLoad,
		onShow,
		onHide,
		onReachBottom,
		onShareAppMessage,
		onShareTimeline,
		onUnload
	} from '@dcloudio/uni-app';

	import ExpandableText from '@/components/ExpandableText/ExpandableText.vue'
	import QrCodeGenerator from '@/components/piaoyi-poster/QrCodeGenerator.vue'
	const loading = ref(true)
	const starIcon = ref('star'); //收藏图标
	const handIcon = ref('hand-up'); //推荐图标

	const posterIf = ref(false);

	const commendModel = ref(''); //评论model
	const videos = ref([]); //该播放的数据信息
	const actors = ref([]); //该播放的演员信息
	const imagesBanner = ref([]); //该播放的摘要
	const nextPage = ref(1); //触底刷新电影
	const popup = ref(''); //触底下一页
	const imgListThrea = ref([]); //触底数据
	const onIndex = ref(0); //切换评论与摘要
	const commendNextPage = ref(1); //触底刷新电影
	const commends = ref([]); //评论
	const commendTotal = ref(0); //评论数量
	const videoId = ref(); //当前的videoId
	const NewVideoUrl = ref(); //video url
	const urlIndexif = ref(true); //播放的效果的开关
	const urlIndex = ref(0); //选集
	const condIconyes = ref("hand-up"); //评论点赞图标
	const condIconno = ref("hand-down"); //评论点赞图标
	const videoUrlSize = ref([]); //剧集的集数
	const seasonValue = ref([]); //剧集关联季
	const urlIndexHidden = ref(); //预选的季数
	const NewVideoId = ref(); //换季之后的新videoId


	// 当前播放时间
	const currentTime = ref(0)

	// 控制视频播放对象
	const videoPlayer = ref(null)
	// 视频最大试看时间（5分钟）
	const maxPreviewTime = 10 * 60 //5 * 60  单位秒

	const showVipModal = ref(false);
	const userSync = ref({})
	// logo 视频
	const textSrc = ref('https://app.erkantv.cn/%E4%B8%AD%E6%96%87/Logo/logo.mp4');
	const videoIf = ref(true);
	const textVideo = ref(true);


	// 获取演员信息
	onLoad((options) => {

		if (options?.scene) {
			console.log("获取的信息scene：", options);
			const sceneParams = parseScene(options.scene);
			const id = sceneParams.id;
			const userId = sceneParams.userId;
			VideoFunction(id)
			videoId.value = id;
			console.log('id:', id, 'userId:', userId);
			uni.setStorageSync("ShareUserId", sceneParams.userId);
			// ✅ 立即验证
			const stored = uni.getStorageSync("ShareUserId");
			console.log("📌 缓存已设置，当前值为:", stored, typeof stored);
		} else {
			console.log("获取的信息：", options);
			// options?.userId
			VideoFunction(options.id)
			videoId.value = options.id;
			if (options?.userId) {
				uni.setStorageSync("ShareUserId", options?.userId);
			}
		}

	})
	onShow(() => {
		// #ifdef MP-WEIXIN
		console.log("用户数据已更新")
		userSync.value = uni.getStorageSync("user");
		console.log("userSync:", userSync.value)

		if (userSync.value.status == 1) {
			showVipModal.value = false
		}
		// #endif


	})
	onHide(() => {
		// console.log('页面退出了')
	})
	onUnload(() => {
		console.log('页面被销毁了（用户返回、关闭等）')
		if (videoId.value) {
			// 存储用户观看记录
			WatchUpdateFunction(userSync.value.id, videoId.value);
			console.log("观看记录以存储")
		}

	})

	// 解析scane数据
	function parseScene(scene) {
		try {
			const decoded = decodeURIComponent(scene);
			const params = {};
			decoded.split('&').forEach(pair => {
				const [key, val] = pair.split('=');
				if (key && val) {
					params[key] = decodeURIComponent(val);
				}
			});
			return params;
		} catch (e) {
			console.error('解析 scene 失败:', e);
			return {};
		}
	}


	// 电影数据
	const VideoFunction = async (id) => {
		let res = await videoById(id);
		let resActor = await actorById(id);
		let resImg = await ImgById(id);

		videos.value = res;
		actors.value = resActor;
		imagesBanner.value = resImg;
		urlIndexHidden.value = res.season;
		// 判断是否已收藏
		collectionCollentFunction(userSync.value.id, id);
		RecommendFunction(userSync.value.id, id);

		if (res.videoUrl) {
			NewVideoUrl.value = res.videoUrl;
			console.log("电影NewVideoUrl：", NewVideoUrl.value);
		} else {
			videoUrlFunction(id).then(url => {
				videoUrlSize.value = url;
				console.log("剧集videoUrl：", url);
				NewVideoUrl.value = url[urlIndex.value].videoUrl;
			});

			seriesVideoFunction(res.seriesId).then(season => {
				seasonValue.value = season;
				console.log("剧集关联季：", season);
			});

		}

		console.log("电影数据:", res);
		// 评论
		commendFunction(commendNextPage.value, id);
	}
	
	const onPlay = () => {
	videoIf.value = false
	}


	// 下部图数据
	const SwiperlistBImg = async (pageNum) => {
		let res = await swiperimgsBanner(pageNum);
		console.log("swiperImg：", res);
		let video = res.data.list
		nextPage.value = res.data.nextPage;
		imgListThrea.value = imgListThrea.value.concat(video);
		for (let i = 0; i < imgListThrea.value.length; i++) {
			if (imgListThrea.value[i].type == 1) {
				imgListThrea.value[i].type = '电影'
			} else if (imgListThrea.value[i].type == 2) {
				imgListThrea.value[i].type = '剧集'
			} else if (imgListThrea.value[i].type == 3) {
				imgListThrea.value[i].type = '综艺'
			} else if (imgListThrea.value[i].type == 4) {
				imgListThrea.value[i].type = '动漫'
			}
		}
		loading.value = false
		console.log("所有的video：", imgListThrea.value);
	}

	// 下部图数据
	SwiperlistBImg(nextPage.value);

	// 评论
	const commendFunction = async (pageNum, id) => {
		let res = await VideoCommend(pageNum, id);
		console.log("commend：", res);
		let commend = res.list;
		commendTotal.value = res.total;
		commendNextPage.value = res.nextPage;
		commends.value = commends.value.concat(commend);
		for (let i = 0; i < commends.value.length; i++) {
			commends.value[i].time = formatTimestamp(commends.value[i].time);
			commends.value[i].condIconyes = 'hand-up';
			commends.value[i].condIconno = 'hand-down';
			console.log(formatTimestamp(commends.value[i].time))
		}
		console.log("所有的评论：", commends.value);
	}

	// 时间码转换
	function formatTimestamp(timestamp) {
		const date = new Date(timestamp);
		const year = date.getFullYear();
		const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始
		const day = String(date.getDate()).padStart(2, '0');
		const hour = String(date.getHours()).padStart(2, '0');
		const minute = String(date.getMinutes()).padStart(2, '0');

		return `${year}/${month}/${day} ${hour}:${minute}`;
	}

	// 剧集Url
	const videoUrlFunction = async (videoId) => {
		let res = await videoUrls(videoId);
		return res;
	}

	// 剧集关联其他季
	const seriesVideoFunction = async (seriesId) => {
		let res = await seriesVideo(seriesId);
		return res;
	}

	// 触底刷新
	onReachBottom(() => {
		if (onIndex.value == 0) {
			if (nextPage.value > 0) {
				console.log("onIndex=0-触底了");
				// 下部图数据
				SwiperlistBImg(nextPage.value);
			}
		}
		if (onIndex.value == 1) {
			if (commendNextPage.value > 0) {
				console.log("onIndex=1-触底了");
				// 下部图数据
				commendFunction(commendNextPage.value, videoId.value);
			}
		}

		console.log("触底了");

	})


	// 点击分享按钮弹窗
	function open() {
		popup.value.open('center')
	};
	// 点击关闭按钮显示弹窗
	function close() {
		popup.value.close()
	}

	// 下部讨论更多参数
	const commentNavbar = ref([{
			id: 1,
			url: '',
			name: '摘要&推荐',
			icon: 'fire'
		},
		{
			id: 2,
			url: '',
			name: '评论',
			icon: 'chat',
			iscomment: true
		},
	])
	// 

	//写一下评论
	function onCommend() {
		console.log("评论发送了", commendModel.value);
		if (!commendModel.value) {
			uni.showToast({
				title: '空字符不能发送！',
				icon: 'none'
			})
			return;
		}
		// 先获取用户信息然后进行存储
		// #ifdef MP-WEIXIN
		let user = uni.getStorageSync("user");
		// #endif

		let username = user.username;
		let userId = user.id;

		let userImg = user.userImg;

		inserFunction(videoId.value, username, userId, commendModel.value, userImg);

	}
	// 评论插入
	const inserFunction = async (videoId, username, userId, content, userImg) => {
		let res = await insertCommend(videoId, username, userId, content, userImg);
		res.time = formatTimestamp(res.time);
		res.condIconyes = 'hand-up';
		res.condIconno = 'hand-down';
		if (res) {
			commends.value.unshift(res);
			//   console.log("最后");
			commendModel.value = '';
		}
		console.log("新插入的评论：", res);
		console.log("新评论数组：", commends.value);
	}

	// 评论夸赞
	function iconClick(e) {
		console.log(e);
		commends.value[e].condIconyes = 'hand-up-filled';
		commends.value[e].condIconno = 'hand-down';
		uni.showToast({
			title: "夸赞！",
			icon: 'none'
		})
	}
	// 评论炸裂
	function iconClickno(e) {
		console.log(e);
		commends.value[e].condIconno = 'hand-down-filled';
		commends.value[e].condIconyes = 'hand-up';

		uni.showToast({
			title: "炸了！",
			icon: 'none'
		})
	}

	// 选集函数
	function xuanjiFunction(e) {
		console.log(e);
		urlIndex.value = e;
		uni.showToast({
			title: `正在播放第${e+1}集`
		});
		console.log("videos-seriesId:", videos.value.season);
		if (urlIndexHidden.value != videos.value.season) {
			VideoFunction(NewVideoId.value);
			urlIndexif.value = true;
		}
		NewVideoUrl.value = [];
		NewVideoUrl.value = videoUrlSize.value[e].videoUrl;
		console.log("index集Url：", videoUrlSize.value[e].videoUrl)
	}

	//选季
	function seasonFunction(e) {
		console.log("选季新VideoId：", e.item.id);
		console.log("选季之前VideoId：", videos.value.id);

		console.log("选季index：", e.index);
		if (e.item.id == videos.value.id) {
			urlIndexif.value = true
		} else {
			urlIndexif.value = false
		}
		urlIndexHidden.value = e.index + 1;
		let videoIds = e.item.id;
		console.log("videos-seriesId:", videos.value.season);
		console.log("urlIndex:", urlIndex.value);
		videoUrlFunction(videoIds).then(url => {
			videoUrlSize.value = url;
			console.log("新剧集videoUrl：", url[0].videoId);
			NewVideoId.value = url[0].videoId;
			videoId.value = url[0].videoId;

		});

	}
	// logo视频播放之后离开关闭
	function onbindended() {
		videoIf.value = false
	}
	// 视频到位出发函数自动调换下一集
	function videoEnded(e) {
		if (videos.value.type == 2 || videos.value.type == 3) {
			console.log("urlIndex.value == videoUrlSize.value.length:", urlIndex.value, videoUrlSize.value.length)
			if (urlIndex.value == videoUrlSize.value.length - 1) {
				uni.showToast({
					title: '本季已结束！！',
					icon: 'none'
				})
				return;
			}
			uni.showToast({
				title: '自动切换下一集！',
				icon: 'none'
			})
			urlIndex.value++;
			console.log("NewVideoUrl.value之前", NewVideoUrl.value);
			NewVideoUrl.value = [];
			NewVideoUrl.value = videoUrlSize.value[urlIndex.value].videoUrl;
			console.log("NewVideoUrl.value之前", NewVideoUrl.value);
			console.log("自动切换集Url：", videoUrlSize.value[urlIndex.value].videoUrl)
		}

		console.log('到剧集结尾了')
	}

	// 监听视频播放时间更新
	function handleTimeUpdate(e) {

		const detail = e.detail
		// console.log("时间码：", detail.currentTime);
		if (detail && detail.currentTime) {
			currentTime.value = detail.currentTime
			if (userSync.value.status == 1) {
				return;
			} else if (videos.value.type == 2 || videos.value.type == 3) {
				if (videoUrlSize.value[urlIndex.value].status == 1) {
					return;
				}
			}

			// videoUrlSize.value[e].videoUrl
			if (detail.currentTime >= maxPreviewTime) {
				// 非会员且播放超过10分钟
				pauseVideo()
				showVipModal.value = true
			}
		}
	}

	// 暂停视频
	function pauseVideo() {
		if (videoContext) {
			videoContext.pause() // ✅ 正确调用 pause 方法
		}
	}
	let videoContext = null;
	onMounted(() => {
		// #ifdef MP-WEIXIN
		let user = uni.getStorageSync("user");
		// #endif
		// 创建视频上下文对象
		videoContext = uni.createVideoContext('myVideo') // 使用 video 的 id
		console.log("加载完成！");
	})



	// 分享等左向按钮开关
	const showDropdown = ref(false);
	// 分享等左向按钮开关函数
	function toggleDropdown() {
		showDropdown.value = !showDropdown.value;
	}
	// 讨论与推荐切换函数
	const onNavbar = (e) => {
		console.log("tags页面：", e);
		onIndex.value = e.index;
	}
	// 返回按钮
	function onBack() {
		// 获取当前页面栈
		const pages = getCurrentPages()
		console.log('当前页面栈:', pages.length)
		if (pages.length > 1) {
			uni.navigateBack({
				delta: 1 // 返回上一个页面
			});
		} else {
			// 已经是第一页，不能返回
			// 可以选择关闭小程序或跳转到首页
			uni.switchTab({
				url: '/pages/index/index'
			})
		}

	}
	// video中的会员按钮
	function huiyuanFunction() {
		uni.navigateTo({
			url: '/pages/alpay/playAlpay/playAlpay'
		})
	}

	// 判断是否已收藏
	const collectionCollentFunction = async (userId, videoId) => {
		let res = await collectionCollent(userId, videoId);
		console.log("收藏：", res);
		if (res.length > 0) {
			starIcon.value = 'star-filled'
		} else {
			starIcon.value = 'star'
		}
	}
	// 进行收藏与取消
	const starFunction = async (e) => {
		uni.showLoading({
			title: '收藏中..'
		})
		console.log("videoID:", e);
		// #ifdef MP-WEIXIN
		let user = uni.getStorageSync("user");
		// #endif
		let res = await insertCollent(user.id, e);
		console.log("插入：", res);
		if (res == 1) {
			starIcon.value = 'star-filled';
			uni.hideLoading();
			uni.showToast({
				title: "已收藏！",
				icon: 'none'
			})

		} else if (res == 2) {
			starIcon.value = 'star';
			uni.showToast({
				title: "收藏已取消！",
			})
		} else {
			uni.showToast({
				title: "收藏失败！",
				icon: 'error'
			})
		}
	}

	// 判断是否已推荐
	const RecommendFunction = async (userId, videoId) => {
		let res = await collectionRecommend(userId, videoId);
		console.log("推荐：", res.list);
		if (res.list.length > 0) {
			handIcon.value = 'hand-up-filled'
		} else {
			handIcon.value = 'hand-up'
		}
	}

	// 进行推荐与取消
	const handFunction = async (e) => {
		uni.showLoading({
			title: '推荐中..'
		})
		console.log("videoID:", e);
		// #ifdef MP-WEIXIN
		let user = uni.getStorageSync("user");
		// #endif
		let res = await insertRecommend(user.id, e);
		console.log("推荐：", res);
		if (res == 1) {
			handIcon.value = 'hand-up-filled';
			uni.hideLoading();
			uni.showToast({
				title: "已推荐！",
				icon: 'none'
			})

		} else if (res == 2) {
			handIcon.value = 'hand-up';
			uni.showToast({
				title: "推荐已取消！",
			})
		} else {
			uni.showToast({
				title: "推荐失败！",
				icon: 'error'
			})
		}
	}


	// 更新观看记录
	const WatchUpdateFunction = async (userId, videoId) => {
		let res = await WatchUpdate(userId, videoId);
		console.log("记录存储：", res);
	}

	// 弹出分享图片形成函数列表
	import piaoyiPoster from '@/components/piaoyi-poster/piaoyi-poster.vue'
	import QRLightGenerator from '@/components/tki-qrcode/QRTripGenerator.vue';

	// ========== 响应式数据 ==========
	const img = ref(null)
	const title = ref('ikran 影视厅')
	const detail = ref('超蓝光，无删减，最新精彩影片')
	const price = ref(95)
	const shopName = ref('我的好母亲')
	const qrImage = ref('');

	// ========== 组件引用 ==========
	const piaoyiPostor = ref(); //绘制ref
	const CodeGenerator = ref() //形成小程序码ref
	const Generator = ref(); //形成通用码ref

	const targetUrl = ref('');
	const logoIcon = ref('/static/logo.png') // 可选：二维码中间的图标
	const paths = ref()

	// 先获取用户信息然后进行存储
	// #ifdef MP-WEIXIN
	let user = uni.getStorageSync("user");
	const userId = ref(user.id);
	// #endif


	// ========== 方法定义 ==========
	const openImg = async (index) => {
		console.log('CodeGenerator:', CodeGenerator.value); // 添加日志
		console.log("qrImage:", qrImage.value)
		uni.showLoading({
			title: "正在生成中..."
		})
		if (index == 1) {
			console.log("小程序码触发")
			CodeGenerator.value?.fetchQrCode()
				.then((qrCodePath) => {
					// 二维码生成成功
					console.log("二维码生成成功，路径:", qrCodePath);
					uni.hideLoading()
					// 打开海报
					piaoyiPostor.value?.open();
					posterIf.value = true;
				})
				.catch((error) => {
					// 二维码生成失败
					console.error("生成二维码失败:", error);
					uni.showToast({
						title: '生成失败',
						icon: 'none'
					});
				});
		} else if (index == 2) {
			// ✅ 先等待 createLink() 执行完成
			const qrPath = await createLink();
			console.log("createLink 执行完成，返回路径:", qrPath);
			setTimeout(() => {
				console.log("通用码触发")
				Generator.value?.generateQR()
					.then((qrCodePath) => {
						// 二维码生成成功
						console.log("二维码生成成功，路径:", qrCodePath);
						uni.hideLoading()

						// 打开海报
						piaoyiPostor.value?.open();
						posterIf.value = true;
					})
					.catch((error) => {
						// 二维码生成失败
						console.error("生成二维码失败:", error);
						uni.showToast({
							title: '生成失败',
							icon: 'none'
						});
					});
			}, 3000); // 延迟 5000 毫秒


		}

	}



	function tempFilePath(filePath) {
		console.log("海报地址：", filePath);
		img.value = null;
		img.value = filePath
	}

	function posterClose() {
		posterIf.value = false;
		uni.hideLoading();
	}
	// 小程序码返回的临时地址
	const onQrCodeSuccess = (filePath) => {
		console.log('小程序码生成成功:', filePath)
		qrImage.value = filePath

	}
	// 通用码返回的临时地址
	const onQRGenerated = (path) => {
		console.log('父页面收到二维码图片路径:', path);
		paths.value = path;
		qrImage.value = path; // 保存路径，可用于预览、上传等
		console.log('通用码生成成功:', path)
	};
	// 海报处理函数
	function shareImgFunction(index) {
		let imgPath = img.value;
		console.log("海报临时地址：", imgPath);
		saveImageToPhotos(imgPath);
	}
	// 将临时图片保存到手机相册
	const saveImageToPhotos = async (tempFilePath) => {
		uni.showLoading({
			title: "处理中..."
		})
		try {
			// 将临时文件保存到本地相册
			await uni.saveImageToPhotosAlbum({
				filePath: tempFilePath
			});
			uni.hideLoading();
			uni.showToast({
				title: '保存成功',
				icon: 'success'
			});
		} catch (err) {
			uni.showToast({
				title: '保存失败',
				icon: 'error'
			});
			console.error('保存图片失败：', err);
		}
	};


	// 获取链接
	const createLink = async (index) => {
		const pages = getCurrentPages()
		const path = pages[pages.length - 1].route // 如 'pages/test/test'
		console.log("path:", path);
		const Id = videoId.value;
		const usersId = userId.value;

		try {
			const [err, res] = await uni.request({
				url: 'https://min.erkantv.cn:8443/api/wx/generate-url-link',
				method: 'POST',
				data: {
					path: path,
					query: 'id=' + Id + '&userId=' + usersId, // ✅ 用 query，不是 scene
					env_version: 'trial',
					expire_type: 1,
					expire_interval: 7
				},
				success(res) {
					console.log('生成的链接:', res.data)
					targetUrl.value = res.data.url_link;
					const urlLink = res.data.url_link;
					// https://wxaurl.cn/Njj1XOIzHfk
					if (index) {
						// ✅ 复制到剪贴板
						uni.setClipboardData({
							data: urlLink,
							success: () => {
								uni.showToast({
									title: '已复制',
									icon: 'success',
									duration: 1500
								});
							},
							fail: () => {
								uni.showToast({
									title: '复制失败',
									icon: 'none'
								});
							}
						});
					}


				}
			})


		} catch (e) {

		}
	}


	// 分享给好友
	onShareAppMessage(() => {
		const shareImageUrl = videos.value.imageUrl;
		const sharePath = `/pages/play/play?id=${videoId.value}&userId=${userId.value}`

		return {
			title: '我分享了一个视频',
			path: sharePath,
			imageUrl: shareImageUrl,
			success: () => uni.showToast({
				title: '分享成功'
			}),
			fail: (err) => console.error('分享失败', err)
		}
	})

	// 分享到朋友圈（可选）
	onShareTimeline(() => {
		return {
			title: '精彩视频，快来围观！',
			query: `id=${videoId.value}&userId=${userId.value}`,
			imageUrl: videos.value.imageUrl
		}
	})


	// #ifdef MP-WEIXIN
	uni.showShareMenu({
		withShareTicket: true,
		menus: ['shareAppMessage', 'shareTimeline']
	})
	// #endif
</script>

<style scoped lang="scss">
	@import '@/uni.scss';

	.video-center {

		background: #1d1d1d;
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;

		.center-text {
			background: #ff0000;
			padding: 20rpx 30rpx;
			box-sizing: border-box;
			border-radius: 20rpx;
		}

		.center-title2 {
			font-size: 22rpx;
			color: #464646;
			padding: 20rpx 0;
		}

		.center-title {
			padding: 20rpx 0;
		}

	}

	.video-content {
		padding: 30rpx;

		.content-title {
			padding: 10rpx 0;
		}

		.video-sort {
			padding: 10rpx 0;
			display: flex;
			align-items: center;
			font-size: 20rpx;
			color: $App-min-text-color;

			& view {
				margin-right: 20rpx;
			}
		}
	}

	.bottum {
		box-sizing: border-box;
		padding: 0 60rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		text-align: center;

		.bottum-Bg {
			background: $App-title-color;
			display: flex;
			align-items: center;
			justify-content: center;
			width: 70rpx;
			height: 70rpx;
			border-radius: 15rpx;
			margin-bottom: 10rpx;
			position: relative;
			z-index: 90;
		}

		.bottum-text {
			font-size: 22rpx;
		}
	}

	.text-title {
		padding: 0 30rpx;

		padding-bottom: 20rpx;
	}

	.image-eight {
		padding: 30rpx;
		display: grid;
		gap: 15rpx;
		grid-template-columns: repeat(2, 1fr);
	}

	.image-eight-Three {
		box-sizing: border-box;
		padding: 20rpx 30rpx;
	}

	.comment {
		width: 100%;
		margin-top: 30rpx;
		padding: 30rpx;
		box-sizing: border-box;
		// background: red;

		.com-user {
			width: 92%;
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 0 30rpx;
			position: absolute;
			box-sizing: border-box;
			margin-top: -40rpx;

			.userImg {
				width: 100rpx;
				height: 100rpx;
				border-radius: 50%;
			}

			.com-SetCount {
				background: $App-max-text-color;
				display: flex;
				align-items: center;
				justify-content: space-between;
				border-radius: 20rpx;
				padding: 15rpx 30rpx;
				width: 120rpx;

				.hand-up {
					display: flex;
					align-items: center;
					justify-content: center;
				}

			}
		}

		.comment-content {
			background: #1d1d1d;
			border-radius: 15rpx;
			padding: 60rpx 0 20rpx 0;

			.com-user-time {
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 20rpx 30rpx;

			}
		}

	}

	.commendfa {
		position: fixed;
		bottom: 10rpx;
		left: 4%;
		width: 92%;
		/* 整体宽度为屏幕的 92%，左右各留 4% 边距 */
		padding: 20rpx 20rpx;
		box-sizing: border-box;
		background: #1d1d1d;
		border-radius: 15rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.fa-input {
		flex: 1;
		background: #464646;
		border-radius: 20rpx;
		padding: 10rpx 20rpx;
		color: #fff;
		font-size: 28rpx;
		margin-right: 20rpx;
		/* 和按钮之间加点间距 */
	}

	.fa-bottum {
		width: 100rpx;
		/* 固定宽度，大约是屏幕宽度的 15%-20% */
		background: #ff0000;
		border-radius: 20rpx;
		padding: 10rpx 20rpx;
		color: #fff;
		text-align: center;
		font-size: 28rpx;
	}

	.han-category-scroll {
		width: 100%;
		padding: 0 10rpx 10rpx 10rpx;
		box-sizing: border-box;

		.category {
			padding: 0 10rpx;
			display: flex;

			.c-item {
				text-align: center;
				margin: 0px 10rpx;

				.usji {
					display: flex;
					flex-direction: column;
					justify-content: center;
					width: 85rpx;
					height: 85rpx;
					border-radius: 15rpx;
					background-color: #1d1d1d;
					color: white;


					.usji-vip {
						background-color: #ff0000;
						padding: 2rpx 10rpx;
						position: absolute;
						top: 0;
						border-top-left-radius: 15rpx;
						border-bottom-right-radius: 10rpx;
					}

					.usji-vip-title {
						font-size: 18rpx;
						color: #fff;
					}
				}


				.c-name {
					margin-top: 10rpx;
					font-size: 26rpx;
					color: #F6F6F6;
				}
			}
		}
	}

	.c-item:last-child {
		padding-right: 30rpx;
	}

	.spinner {
		display: inline-block;
		text-align: center;
		height: 40rpx;
	}

	.spinner>view {
		background-color: #FF0000;
		height: 40rpx;
		width: 8rpx;
		display: inline-block;
		animation: stretchdelay 1.2s infinite ease-in-out;
	}

	.spinner .rect2 {
		animation-delay: -1.5s;
	}

	.spinner .rect3 {
		animation-delay: -1.2s;
	}

	.spinner .rect4 {
		animation-delay: -0.9s;
	}

	@keyframes stretchdelay {

		0%,
		40%,
		100% {
			transform: scaleY(0.4);
		}

		20% {
			transform: scaleY(1.0);
		}
	}


	.han-category-scroll ::-webkit-scrollbar {
		width: 0;
		height: 0;
		color: transparent;
		display: none;
	}

	.poster-img {
		width: 100%;
		height: 100vh;
		position: fixed;
		z-index: 1000;
		top: 0;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		background-color: rgba(0, 0, 0, 0.8);
		overflow: hidden;

		.poster-icon {
			width: 100%;
			display: flex;
			position: relative;
			box-sizing: border-box;
			padding: 20rpx 50rpx;
			align-items: center;
			justify-content: space-between;
		}

		.share {
			position: relative;
			z-index: 100;
			margin-top: 40rpx;
			border-radius: 20rpx;
			background-color: #ff0000;
			padding: 20rpx 100rpx;
		}
	}

	.share-pop {
		margin-top: -50rpx;
		width: 100%;
		padding: 0 20rpx;
		display: flex;
		flex-wrap: wrap;
		/* ✅ 允许换行 */
		align-items: center;
		/* justify-content: space-between; 删除或保留看布局需求 */
	}

	.pop-item {
		position: relative;
		z-index: 1000;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-direction: column;
		width: 25%;
		/* ✅ 一行最多4个，每个占 25% */
		box-sizing: border-box;
		height: 200rpx;

		/* 可选：给每行之间加点间距 */
		.b-abs {
			position: static;
			/* 确保不是 relative/absolute 影响布局 */
			border: none;
			background: transparent;
			// padding: 0;
			// margin: 0;
			margin-bottom: -20rpx;
			// width: 60rpx;
			// /* 固定宽高，避免按钮默认宽高 */
			// height: 60rpx;
		}

	}
</style>